package com.building18.service.impl;

import com.building18.handler.MyAssert;
import com.building18.mapper.RoleMapper;
import com.building18.pojo.Result;
import com.building18.pojo.Role;
import com.building18.pojo.User;
import com.building18.pojo.enums.Code;
import com.building18.pojo.vo.RoleVO;
import com.building18.service.PermissionService;
import com.building18.service.RoleService;
import com.building18.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public List<RoleVO> getRoles(Integer id) {
        List<RoleVO> allRoles = roleMapper.getRoles();
        List<RoleVO> rolesByUid = this.getRolesByUid(id);
        //所有角色信息中 哪个行应该被选中【1,2,3,4】 【1，3】
        for (RoleVO role : allRoles) {
            for (RoleVO userRole : rolesByUid) {
                if(userRole.getRoleId().equals(role.getId())){
                    role.setFlg(true);
                }
            }
        }
        return allRoles;
    }

    @Override
    public List<RoleVO> getRolesByUid(Integer id) {
        return roleMapper.getRolesByUid(id);
    }

    @Override
    @Transactional //开启事务,方法内，所有的sql同时共享一个事务
    public Integer saveRole(Integer uid, List<Integer> roleIds) {
        //1. 根据uid删除用户原本的角色信息 delete
        Integer num1 = roleMapper.deleteRolesByUid(uid);
        //2. 根据uid新增用户的新的角色信息 insert
        if(!roleIds.isEmpty()){
            num1 = roleMapper.saveNewRoles(uid, roleIds);
        }
        MyAssert.error(num1<=0, Code.UPDATE_FAIL.getMessage());
        return num1;
    }


    @Override
    public List<RoleVO> selectRoles() {
        return roleMapper.selectRoles();
    }

    @Override
    public Integer deleteRole(Integer id) {
        userService.beforeDeleteRole(id);
        permissionService.beforeDeleteRole(id);
        return roleMapper.deleteRole(id);
    }

    @Override
    public Integer updateRole(Role role) {
        return roleMapper.updateRole(role);
    }

    @Override
    public Role selectRole(Integer id) {
        return roleMapper.selectRole(id);
    }
}
